package nuder;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;

import titt.TITT;
import titt.TITTNuder;
import titt.head.response.FileHead;
import titt.io.IOFactory;
import titt.service.content.NuderRequest;
import titt.service.content.NuderResponse;
import titt.util.debug.Printer;
import titt.util.io.pipe.PipeListener;
import titt.util.io.pipe.StreamPiper;


public class PuffGet {
	public class Monitor {
		public void onComplete(int total, String[] ids) {}
		public void onConnectionUpdate(int read, int total, String[] ids) {}
		public void onError(String[] ids) {}
		public void onInitiate(int total, String[] ids) {}
	}

	public interface KKloudFileStream {	NuderResponse get(); }
	public interface KKloudFile { NuderResponse puff(String id, int updateInterval, NuderRequest req); 
	NuderResponse foo(NuderRequest req);}
	
	public static void main(String... args) throws Exception {
		new PuffGet().puff();
	}
	
	public void puff() throws Exception {
		String id = "foo";
		File f = new File("f.mp3");
		Monitor monitor = new Monitor();

		TITT.config(80, "kkloud.dk");
		TITT.register(monitor, "kkloud", "manager", "monitor", id);
		KKloudFile proxy = TITTNuder.createProxy("kkloud", "file");
		proxy.puff(id, 1500, new NuderRequest(f));
		TITT.unregister(monitor);
	}
	
	public void get() throws Exception {
		TITT.config(80, "kkloud.dk");
		KKloudFileStream kfs = TITTNuder.createProxy("foo");
		NuderResponse nr = kfs.get();
		FileHead fh = new FileHead(nr.getHead());
		String filename = fh.getFilename();
		int length = nr.getLength();
		System.out.println("Fetching: '" + filename + "'");
		System.out.println("Length: " + (length / 1024) +  "kb");
		StreamPiper sp = IOFactory.createStreamPiper();
		sp.pipe(nr.getStream().asStream(), new BufferedOutputStream(new FileOutputStream(filename)), length, new PipeListener() {
			public void onComplete(int total) {
			}
			public void onConnectionUpdate(int read, int total) {
			}
			public void onError() {
			}
			public void onInitiate(int total) {
			}
		});
		Printer.printHead(nr.getHead());
	}
}

